package com.example.heathy_me.homeDetail;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.heathy_me.MainActivity;
import com.example.heathy_me.MyApplication;
import com.example.heathy_me.R;
import com.example.heathy_me.utils.Notice;
import com.example.heathy_me.utils.NoticeList;
import com.example.heathy_me.utils.RequestHelper;
import com.example.heathy_me.utils.ScreenControlAlarmReceiver;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Medicine extends AppCompatActivity {
    private Notification mNotification;
    private NotificationManager notificationManager;
    private PendingIntent mResultIntent;
    private TimePicker timepick;
    private LinearLayout add_title;
    private ImageView add;
    private Button btn;
    private EditText title;
    private ListView listview;
    private TextView hos;
    private Boolean is_add=false;
    MyApplication app;
    private List<Map<String,String>> list_map = new ArrayList<Map<String,String>>();
    private List<Notice> noticelist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medicine);
        hos = findViewById(R.id.hos);
        title = findViewById(R.id.title);
        btn = findViewById(R.id.add_title_btn);
        add = findViewById(R.id.add_medicine);
        timepick =findViewById(R.id.timepick);
        add_title =findViewById(R.id.add_title);
        listview = (ListView)findViewById(R.id.medicine_list);
        app = (MyApplication)getApplication();
        //notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, MainActivity.class);
        mResultIntent = PendingIntent.getActivity(this, 1, intent,
                Intent.FILL_IN_ACTION);
        try {
            get_friendlist(false);
            setList();
        } catch (IOException e) {
            e.printStackTrace();
        }
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent=new Intent(Medicine.this, Add_medicine.class);
                //startActivity(intent);
                //sendNotification(v);
                changeMode();

            }
        });
        listview.setClickable(true);
        listview.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView parentView, View childView, int position, long id) {
                Toast.makeText(Medicine.this,position+"+"+id,Toast.LENGTH_SHORT).show();
            }
            public void onNothingSelected(AdapterView parentView) {

            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent=new Intent(Medicine.this, Add_medicine.class);
                //startActivity(intent);
                //sendNotification(v);
                if (add_friend(timepick.getHour(),timepick.getMinute(),title.getText().toString()))
                {
                    setTime(timepick.getHour(),timepick.getMinute());
                    Toast.makeText(Medicine.this,"设置提醒成功",Toast.LENGTH_SHORT).show();
                    try {
                        get_friendlist(false);
                        setList();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
                changeMode();
            }
        });


        //listview = (ListView) findViewById(R.id.cardlistView);
        /*
        SimpleAdapter simpleAdapter=new SimpleAdapter(this,list_map,R.layout.medicine_item,new String[]{"time","title"},new int[]{R.id.medicine_time,R.id.medicine_title});
        listview.setAdapter(simpleAdapter);
        listview.setTextFilterEnabled(true);
        listview.setVisibility(View.VISIBLE);*/

        //listview.setAdapter(simpleAdapter);
        //setContentView(R.layout.activity_mian_water);
        //获取到通知管理器






    }
    // 为发送通知的按钮的点击事件定义事件处理方法
    public void sendNotification(View view){
        String id = "my_channel_01";
        String name="渠道名字";
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = null;

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle("5 new messages")
                    .setContentText("hahaha")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setOngoing(true)
                    .setChannelId(id);//无效
        notification = notificationBuilder.build();

        notificationManager.notify(111123, notification);


    }
    void setList()
    {

        list_map = new ArrayList<Map<String,String>>();
        for (int i=0;i<noticelist.size();i++)
        {
            Map<String,String> items = new HashMap<String, String>(); //创建一个键值对的Map集合
            items.put("time", noticelist.get(i).getHour()+"："+noticelist.get(i).getMinute());
            items.put("title",  noticelist.get(i).getTitle());
            list_map.add(items);   //把这个存放好数据的Map集合放入到list中，这就完成类数据源的准备工作
        }


        SimpleAdapter simpleAdapter=new SimpleAdapter(Medicine.this,list_map,R.layout.medicine_item,new String[]{"time","title"},new int[]{R.id.medicine_time,R.id.medicine_title});
        listview.setAdapter(simpleAdapter);
        listview.setTextFilterEnabled(true);
        listview.setVisibility(View.VISIBLE);
    }
    void setTime(int hour,int minute)
    {
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.HOUR_OF_DAY, hour);//小时
        instance.set(Calendar.MINUTE, minute);//分钟
        instance.set(Calendar.SECOND, 0);//秒
        AlarmManager alarmService = (AlarmManager) this.getSystemService(ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, ScreenControlAlarmReceiver.class).setAction("intent_alarm_log");
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);//通过广播接收
        alarmService.set(AlarmManager.RTC_WAKEUP, instance.getTimeInMillis() , broadcast);
    }
    void changeMode()
    {
        if(!is_add)
        {
            timepick.setVisibility(View.VISIBLE);
            add_title.setVisibility(View.VISIBLE);
            listview.setVisibility(View.GONE);
            hos.setVisibility(View.GONE);
        }
        else {
            timepick.setVisibility(View.GONE);
            add_title.setVisibility(View.GONE);
            listview.setVisibility(View.VISIBLE);
            hos.setVisibility(View.VISIBLE);
        }
        is_add=!is_add;
    }
    Boolean add_friend(int hour, int minute,String title)
    {
        RequestHelper req = new RequestHelper();
        Map map = new HashMap();
        map.put("user_id", app.getUser().getId());
        map.put("hour", hour);
        map.put("minute",minute);
        map.put("title",title);
        JSONObject json = new JSONObject(map);
        try {
            String json_str = req.friend_post(app.getUrl()+"notice/add",json.toString());
            JSONObject jsonObject = new JSONObject(json_str);
            int status = jsonObject.getInt("status");
            if (status==1){
                return true;
            }else {
                return false;
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return false;
        }

    }
    void get_friendlist(Boolean is_notice) throws IOException {
        RequestHelper req = new RequestHelper();
        String json = req.friend_get(app.getUrl()+"notice?user_id="+ app.getUser().getId()+"&is_notice="+is_notice);
        Gson gson = new Gson();
        //把JSON数据转化为对象
        NoticeList notice = gson.fromJson(json, NoticeList.class);
        noticelist = notice.getNotices();
    }

}


